<?php

namespace App\Http\Controllers\Client\Auth;

use App\Http\Controllers\RootController as Controller;
use App\Models\Member\Member;
use App\Models\Old\Personal;
use App\Models\School\School;
use App\Services\Auth\PasswordTokenService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class LoginByMobileController extends Controller
{
    public function handle(Request $request)
    {
        $param['mobile'] = (string)$request->input('mobile', '');
        $param['password'] = trim($request->input('password', ''));

        $rules    = [
            'mobile'  => 'required',
            'password' => 'required',
        ];
        $messages = [
            'mobile.required'                    => '请输入手机号',
            'password.required'                   => '请输入密码',
        ];

        if (true !== ($error = $this->validator($param, $rules, $messages)))
        {
            return $this->failure($error, 'VALIDATION_FAIL');
        }


        $member = Member::where('mobile', $param['mobile'])->first();
        if(empty($member)) return $this->failure('该工作人员不存在');

        if($member->pwd != md5($param['password']))  return $this->failure('密码不正确');

        try
        {
            // 创建登录 token
            list($statusCode, $content) = PasswordTokenService::make(
                $param['mobile'],
                '',
                'members',
                '1',
                'vKRaGoNYG0yO4nNvHL1jDDXgIL144pnSSXD1JN5c'
            );

            if((200 !== $statusCode)) throw new \Exception($content);

            return $this->success($content);
        }
        catch (\Exception $e)
        {
            DB::rollBack();
            return $this->failure($e->getMessage().$e->getLine().'登录失败');
        }
    }
}
